//2.2.4创建my-menu.js，显示树形结构

$(function () {

    initWholeTree();


})

//2.2.6声明函数将图标修改为自定义图标


//原理修改每个节点的class

function showMyIcon(treeId, treeNode) {
    //输出 数据
    console.log(treeId);//是 -多少
    console.log("---------------------");
    console.log(treeNode);//treeNode是 class id是前面的treeDemo
    //获取当前节点的id
    var currentNotedId = treeNode.tId;
    //获取新的class值用于替换
    var newClass = treeNode.icon;
    //在当前节点id上加上"_ico"获得目标span的id
    var targerSpanId = currentNotedId + "_ico";
    $("#" + targerSpanId).removeClass().addClass(newClass).css("background", "")
}

//3.4声明函数生成按钮组
//生成并返回按钮组
function generateBtnGrp(treeNode) {
    var tid = treeNode.tId;//当前节点id
    var btnGrpSpanId = tid + "_btnGrp";//组装按钮所在span的id
    //生成span标签
    var $span = $("<span id='" + btnGrpSpanId + "'><span/>")
    var menuId = treeNode.id;
    var level = treeNode.level;

    // 声明三种按钮
    var addBtn = "<a onclick='showAddModal(this)' id='" + menuId + "' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='添加子节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-plus rbg'></i></a>";
    var editBtn = "<a onclick='showEditModal(this)' id='" + menuId + "' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='编辑节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-edit rbg'></i></a>";
    var removeBtn = "<a onclick='showConfirmModal(this)' id='" + menuId + "' class='btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' title='删除节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-times rbg'></i></a>";

    //根据level进行判断
    if (level == 0) {
        $span.append(addBtn);
    } else if (level == 1) {
        if (treeNode.children.length > 0) {
            $span.append(addBtn + " " + editBtn);
        } else {
            $span.append(addBtn + " " + editBtn + " " + removeBtn);
        }
    } else {
        $span.append(editBtn + " " + removeBtn);
    }
    return $span;


}

//addHoverDom(treeId, treeNode)函数
function addHoverDom(treeId, treeNode) {
    var btnGrpSpanId = treeNode.tId + "_btnGrp";//组装按钮所在span的id
    var btnGrpSpanLength = $("#" + btnGrpSpanId).length;
    if (btnGrpSpanLength > 0) {
        return;
    }
    //获取按钮组
    var $btnGrpSpan = generateBtnGrp(treeNode);
    // 由于按钮组是放在当前节点中的超链接（a标签）后面，所以先定位到a标签
    // 按id生成规则组装a标签的id
    var anchorId = treeNode.tId + "_a";
    //a标签里面 span后面 追加  按钮组
    $("#" + anchorId).append($btnGrpSpan);
}

//3.6removeHoverDom(treeId, treeNode)函数
//鼠标移出节点时调用此方法
function removeHoverDom(treeId, treeNode) {
    // 组装按钮组所在的span标签的id
    var btnGrpSpanId = treeNode.tId + "_btnGrp";
    //删除对应的span标签
    $("#" + btnGrpSpanId).remove();
}

//添加菜单
function showAddModal(currentBtn) {
//打开莫泰框
    $("#menuAddModal").modal('show');
    //将当前节点的id存入全局变量
    window.menuId = currentBtn.id;
}

//给保存按钮绑定单机响应事件
$("#menuAddBtn").click(function () {
    //收集表单填写的数据
    /*  var name=$.trim($("#menuAddModal [name='name']").val());
      var url=$.trim($("#menuAddModal [name='url']").val());
      var icon = $("#menuAddModal [name='icon']:checked").val();*/

    var name = $.trim($("#menuAddModal [name='name']").val());
    var url = $.trim($("#menuAddModal [name='url']").val());
    var icon = $("#menuAddModal [name='icon']:checked").val();

    if (name == null || name == "") {
        layer.msg("请填写菜单项名称！");
        return;
    }
    if (url == null || url == "") {
        layer.msg("url菜单项名称！");
        return;
    }


// 发送Ajax请求
    $.ajax({
        "url": "/menu/save",
        "type": "post",
        "dataType": "json",
        "data": {
            "name": name,
            "url": url,
            "pid": window.menuId,   // 当前操作的节点是新节点的父节点
            "icon": icon
        },
        "success": function (response) {

            var result = response.result;

            if (result == "SUCCESS") {
                layer.msg("操作成功！");

                initWholeTree();
            }

            if (result == "FAILED") {
                layer.msg(response.message);
            }

        },
        "error": function (response) {
            layer.msg(response.message);
        }
    });


    $("#menuAddModal").modal('hide');
})


function initWholeTree() {
    //setting对象中包括zTree的属性
    var setting = {
        "view": {
            "addDiyDom": showMyIcon,
            "addHoverDom": addHoverDom,
            "removeHoverDom": removeHoverDom
        },
        "data": {
            "key": {
                "url": "notExistsProperty" // 阻止点击节点后跳转
            }
        }
    }

    //发送ajax请求
    $.ajax({
        url: "/menu/get/whole/tree",
        type: "post",
        dataType: "json",
        success: function (ajaxResult) {
            var result = ajaxResult.result;
            if (result == "SUCCESS") {
                //用于显示树形结果的节点数据
                var zNodes = ajaxResult.data;

                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            } else {
                layer.msg("加载菜单数据失败！原因是：" + response.message);
            }
        }
    })
}

//修改
// 在点击编辑按钮时执行这个函数，打开模态框
function showEditModal(currentBtn) {

    // 打开模态框
    $("#menuEditModal").modal("show");

    // 获取当前节点的id存入全局变量
    window.menuId = currentBtn.id;

// 发送请求查询Menu对象
    $.ajax({
        "url": "/menu/get/" + window.menuId,
        "type": "get",
        "dataType": "json",
        "success": function (response) {
            var result = response.result;
            if (result == "SUCCESS") {
                // 从响应数据中获取Menu对象
                var menu = response.data;
                // 获取各个属性值
                var name = menu.name;
                var url = menu.url;
                var icon = menu.icon;

                // 设置各个对应的表单项
                $("#menuEditModal [name='name']").val(name);

                $("#menuEditModal [name='url']").val(url);

                // radio需要让value值和后端查询到的icon一致的设置为被选中
                $("#menuEditModal [name='icon'][value='" + icon + "']").attr("checked", true);
            }

            if (result == "FAILED") {
                layer.msg(response.message);
            }
        },
        "error": function (response) {
            layer.msg(response.message);
        }
    });
}


//确定修改
/*
$("#menuEditBtn").click(function () {
    // 收集表单填写的数据
    var name = $.trim($("#menuEditModal [name='name']").val());
    var url = $.trim($("#menuEditModal [name='url']").val());
    var icon = $("#menuEditModal [name='icon']:checked").val();

    if (name == null || name == "") {
        layer.msg("请填写菜单项名称！");
        return;
    }
    if (url == null || url == "") {
        layer.msg("url菜单项名称！");
        return;
    }

    //修改的ajax
    $.ajax({
        url:"/menu/update",
        type:"post",
        dataType:"josn",
        data:{
            "id":window.menuId,
            "name":name,
            "url":url,
            "icon":icon
        },
        success:function (ajaxResult) {
            if(ajaxResult.result=="SUCCESS"){
                layer.msg("修改成功");
            initWholeTree();
            }else{
                layer.msg(response.message);
            }
        }
    })

    $("#menuEditModal").modal("hide");
})

*/

$("#menuEditBtn").click(function () {
    //确定修改
    var name = $.trim($("#menuEditModal [name='name']").val());
    var url = $.trim($("#menuEditModal [name='url']").val());
    var icon = $.trim($("#menuEditModal [name='icon']:checked").val());
    if (name.length == 0) {
        return;
    }
    if (url.length == 0) {
        return;
    }

    //ajax修改

    $.ajax({
        url: "/menu/update",
        type: "post",
        data: {
            "id": window.menuId,
            "name": name,
            "url": url,
            "icon": icon
        },
        dataType: "json",
        success: function (ajaxResult) {
            if (ajaxResult.result == "SUCCESS") {
                layer.msg("修改成功");
                initWholeTree();
            } else {
                layer.msg("修改失败");
            }
        }
    })
//关闭 模态框
    $("#menuEditModal").modal('hide');

})


function showConfirmModal(obj) {
    window.menuId = $(obj).attr("id");

    //获取节点名称
    var name = $(obj).parent().prev().text();
    var r = confirm("确认删除" + name + "菜单吗!");
    if (r == false) {
        return;
    }

    //发送ajax
    $.ajax({
        "url": "/menu/delete/" + window.menuId,
        "type": "get",
        "dataType": "json",
        "success": function (response) {
            var result = response.result;

            if (result == "SUCCESS") {
                layer.msg("操作成功！");

                initWholeTree();
            }

            if (result == "FAILED") {
                layer.msg("操作失败,请联系管理员");
            }
        }

    });

}

